// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function setupAjax() {
  img = $('<img/>', { alt: 'Loading', src: '/images/loading.gif' });
  img_div = $('<div/>', { id: 'loading_img' });  
  loading_div = $('<div/>', { id: 'loading' });
  $("body").append(loading_div.append(img_div.append(img)));
  $("#loading").ajaxStart(function(){
    $(this).show();
  }).ajaxComplete(function(){
    $(this).hide();
  });
}
function loadEditors() {
  var $editors = $("textarea.content");
  if ($editors.length) {
    $editors.each(function() {
      var editorID = $(this).attr("id");
      var instance = CKEDITOR.instances[editorID];
      // if (instance) { CKEDITOR.remove(instance) }
      if (instance) { instance.destroy(); }
      CKEDITOR.replace(editorID);
    });
  }
  // CKEDITOR.replaceClass = 'content';
}
function loatRemoveContentByAjax() {
  $(".remove_text_ajax").removeContentByAjax();
  $(".remove_source_ajax").removeContentByAjax();
}
/******************************************************
 * jQuery Code Collector Specification Plugin
 * @requires jQuery v1.4 or later
 *
*******************************************************/	
(function($) {
var CONTENT_COUNT = parseInt($("textarea[name='content[]']").size()) + 1;
var SOURCE_COUNT = parseInt($("textarea[name='source[]']").size()) + 1;
var LANGUAGES = [
  //Displayed           stored in DB
  ["C",                 "c"],
  ["C++",               "c++"],
  ["CSS",               "css"],
  ["Css Experimental",  "css_experimental"],    
  ["HAML",              "haml"],
  ["HTML for Rails",    "html_rails"],      
  ["Javascript",        "javascript"],
  ["jQuery",            "jquery_javascript"],
  ["Objective-C",       "objective-c"],  
  ["Objective-C++",     "objective-c++"],
  ["Ruby on Rails",     "ruby_on_rails"],  
  ["Ruby",              "ruby"]  
]
function createTag(textarea_prefix, textarea_name, textarea_class, count, remove_link_class_name) {
  // Make a warp div.   
  div = $('<div/>', { class: 'from_row' });
  // Make a textarea.
  textarea = $('<textarea/>', { id: textarea_prefix + count, name: textarea_name, class: textarea_class }); 
  // Make a p tag.   
  p = $('<p/>', { class: 'btn clearfix' }); 
  // Make a link can be remove the warp div and all the content in it.  
  remove_link = $('<a/>', { href: 'javascript:void(0)', class: remove_link_class_name, text: 'Remove' });   
}           
/******************************************************
 * Toggle button_warp visible or hidden.
 * @example
 * $("#add_content").addContent();
 *
*******************************************************/	
$.fn.addText = function() {    
	var $this = $(this);
	$this.click(function() {
	  CONTENT_COUNT++; 
    createTag('content_', 'contents[body][]', 'content', CONTENT_COUNT, 'remove_text');
    content_id = $('<input/>', { type: 'hidden', name: 'contents[id][]', value: '' });
    language_type = $('<input/>', { type: 'hidden', name: 'contents[language_type][]', value: 'text' });
    $this.serialTag(div, textarea, p, remove_link, content_id, language_type);
    // CKEDITOR.replace($("textarea[name='contents[body][]']:last").attr("id"));
    // $("textarea[name='contents[body][]']:last").ckeditor();
    loadEditors();
    $(".remove_text").removeFormRow();
	})
}
/******************************************************
 * Toggle button_warp visible or hidden.
 * @example
 * $("#add_source").addSource();
 *
*******************************************************/
$.fn.addSource = function() {    
	var $this = $(this);
	$this.click(function() {
	  SOURCE_COUNT++;  
    createTag('source_', 'contents[body][]', 'source', SOURCE_COUNT, 'remove_source');
    content_id = $('<input/>', { type: 'hidden', name: 'contents[id][]', value: '' });    
    // Create a select, option is a list of languages.    
    select = $('<select/>', { name: 'contents[language_type][]' });
    for(var i = 0; i < LANGUAGES.length; i++) {
      option = $('<option/>', {
        text: LANGUAGES[i][0],      
        value: LANGUAGES[i][1]      
      });
      select.append(option);
    }
    span = $('<span/>', { class: 'right' });
    label = $('<label/>', { text: 'Language: ' });
    p.prepend(span.prepend(select).prepend(label));
    $this.serialTag(div, textarea, p, remove_link, content_id);
    $(".remove_source").removeFormRow();
	})
}
// Insert warp div with textarea before P tag of the submit.
$.fn.serialTag = function(div, textarea, p, remove_link, content_id, language_type) {
  remove_link.html("<span>Remove</span>")  
  p.prepend(remove_link);
  return $(this).parents("p").before(div.prepend(textarea).prepend(p).prepend(content_id).prepend(language_type));
}
// When click remove button, will delete this parent div with class from_row.
$.fn.removeFormRow = function() {
  return this.each(function() {
    var $this = $(this); 
    $this.click(function() {
      // Destroys the editor instance, releasing all resources used by it. VERY IMPORTANT!!!
      $this.destroyCkedit();
      $this.parents("div.from_row").remove();
    })
  })
}
// When click remove button, will delete this parent div with class from_row.
$.fn.removeContentByAjax = function() {
  return this.each(function() {
    var $this = $(this); 
    $this.click(function() {
      if(confirm('Are you sure?')) {
        var url = $this.attr("href");
        $.post(url, function() {
          // Destroys the editor instance, releasing all resources used by it. VERY IMPORTANT!!!
          $this.destroyCkedit();
          $this.parents("div.from_row").remove();
        });
        return false;        
      }
    })
  })
}
/******************************************************
 * Destroys the editor instance, releasing all resources used by it.
 * If the editor replaced an element, the element will be recovered.
 * @example
 * $this.destroyCkedit();
 * @more
 * http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.editor.html#destroy
 *  
*******************************************************/
$.fn.destroyCkedit = function() {
  var $this = $(this); 
  instance = CKEDITOR.instances[$this.parents("div.from_row").find("textarea").attr("id")];
  if(instance) { instance.destroy(); }
}

/******************************************************
 * Easy plugin for managing tag list.
 * @example
 * $("#all_tags").tags();
 *
*******************************************************/
$.fn.tags = function() {
  var $this = $(this);
  $("span", $this).each(function() {
    var $tag = $(this);
    $tag.click(function() {
      $tag.toggleClass("selected");
      var tag_list = ""
      $("span.selected", $this).each(function() {
        tag_list += $(this).html() + " ";
      })
      $("#article_tag_list").val(tag_list);
    })
  })
}
})(jQuery);